package com.sharer.last.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户登出处理器
 *
 * @ClassName LogoutHandler
 * @Author WangJin
 * @Date 2023/05/10/15:40
 * @Description
 * @Version 1.0
 */
public class UserLogoutHandler implements LogoutHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserLogoutHandler.class);

    @Resource
    private TokenStore tokenStore;

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        String token = request.getHeader("Authorization");
        OAuth2AccessToken existingAccessToken = this.tokenStore.readAccessToken(token);
        if (existingAccessToken != null) {
            OAuth2RefreshToken refreshToken = existingAccessToken.getRefreshToken();
            if (refreshToken != null) {
                LOGGER.info("remove refreshToken!--{}", refreshToken);
                this.tokenStore.removeRefreshToken(refreshToken);
            }

            LOGGER.info("remove existingAccessToken!--{}", existingAccessToken);
            this.tokenStore.removeAccessToken(existingAccessToken);
        }
    }
}
